﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using TFSLBALib;

namespace WITSynchronizer
{
	/// <summary>
	/// This class implements a pool of ProcessTemplate objects
	/// The user asks for a Process Template object for the given nammed one.
	/// The pool can be recycled anytime.
	/// </summary>
	class ProcessTemplatePool : IDisposable
	{
		#region Data members

		/// <summary>
		/// Dictionary that list all the ProcessTemplate objects by their name
		/// </summary>
		Dictionary<String, ProcessTemplate> PoolDic = new Dictionary<string, ProcessTemplate>();
		
		/// <summary>
		/// Used Team Foundation Server object
		/// </summary>
		TeamFoundationServer				TFS = null;

		#endregion

		#region Constructor

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="tfs">TFS Object to user</param>
		public  ProcessTemplatePool(TeamFoundationServer tfs)
		{
			TFS = tfs;
		}

		#endregion

		/// <summary>
		/// Dispose implementation, flush the pool
		/// </summary>
		public void Dispose()
		{
			FlushPool();
		}

		/// <summary>
		/// Get a ProcessTemplate object from its name
		/// </summary>
		/// <param name="name">The name of the Process Template to get the object from</param>
		/// <returns>The ProcessTemplate object or null if the given name doesn't refer to an existing Process Template</returns>
		public ProcessTemplate this[string name]
		{
			get
			{
				// Try to get the Zip file from the pool
				ProcessTemplate pt = null;
				if (PoolDic.TryGetValue(name, out pt) == true)
				{
					return pt;
				}

				// Couldn't find it, load it
				try
				{
					pt = new ProcessTemplate(TFS, name);
					PoolDic.Add(name, pt);
				}
				catch (Exception e)
				{
					e.ToString();
				}

				return pt;
			}
		}

		/// <summary>
		/// Flush the Pool, release all the resources
		/// </summary>
		public void FlushPool()
		{
			foreach (KeyValuePair<string, ProcessTemplate> pair in PoolDic)
			{
				pair.Value.Dispose();
			}
			PoolDic.Clear();
		}
	}
}
